package com.iwhalecloud.bss.kite.cucc.service.attr.linkhandler;

import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.inf.IInfServiceBus;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.SaleManageDTO;
import com.iwhalecloud.bss.kite.cucc.service.attr.handler.LocalSalesmanAttrHandler;
import com.iwhalecloud.bss.kite.listener.handler.attr.annotation.AttrHandler;
import com.iwhalecloud.bss.kite.listener.handler.attr.impl.AbstractAttrLinkageHandler;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
@AttrHandler(LocalSalesmanAttrHandler.class)
public class LocalSalesmanAttrLinkHandler extends AbstractAttrLinkageHandler<AttrData> {

    @Resource
    private IInfServiceBus infServiceBus;

    @Override
    public void handle(KiteAttr attr, KiteInst inst, AttrData data) {
        KiteAttr saleIdAttr = inst.getAttr("200003989");
        if (Objects.nonNull(saleIdAttr) && KiteStringUtils.isNotEmpty(attr.getValue())) {
            String saleId = getSalesmanId(attr.getValue());
            if (KiteStringUtils.isNotEmpty(saleId)) {
                saleIdAttr.setValue(saleId);
                saleIdAttr.setValueDesc(saleId);
            }
        }
    }

    @Override
    public void handleStyle(KiteAttr attr, KiteInst inst, AttrData data) {

    }

    private String getSalesmanId(String value) {
        // FIXME : 只能查出所有销售人员列表，再遍历匹配名称，然后返回对应id。若有有新的方案请优化。
        List<SaleManageDTO> saleManageDTOs = infServiceBus.querySaleManager(null, null, "", null, null);
        return saleManageDTOs.stream().filter(saleManageDTO -> KiteStringUtils.equals(value, saleManageDTO.getName()))
            .findFirst().map(SaleManageDTO::getSaleId).orElse("");
    }
}
